package com.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @Description 基础
 * @Author hyl
 * @Date 2022/4/18 15:19
 **/
public class BaseDao {
	private static String driver;// = "com.mysql.cj.jdbc.Driver";
	private static String url;// = "jdbc:mysql://127.0.0.1:3306/hospitaldb?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8";
	private static String username;// = "root";
	private static String pwd;// = "root";

	static {
		init();
	}
	//初始化==》解析Propertis文件，为变量赋值
	public static void init(){
		Properties properties = new Properties();
		//使用InputStream 解析文件
		InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("database.properties");
		try {
			//加载
			properties.load(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		driver = properties.getProperty("mysql.driver");
		url = properties.getProperty("mysql.url");
		username = properties.getProperty("mysql.name");
		pwd = properties.getProperty("mysql.pwd");

	}

	/**
	 * 获取链接
	 * @return
	 */
	public Connection getConnection(){
		//1、加载驱动
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		Connection conn = null;
		//2、创建链接对象
		try {
			conn = DriverManager.getConnection(url,
					username, pwd);
		}catch (SQLException e){
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 释放资源
	 * @param conn
	 * @param stm;
	 * @param rs
	 */
	public void closeAll(Connection conn, Statement stm, ResultSet rs){
		//7、释放资源
		try {
			if(rs != null) {
				rs.close(); //NullPointException
			}
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}
		try {
			if(stm != null) {
				stm.close();
			}
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}
		try {
			if(conn!=null) {
				conn.close();
			}
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}
	}

}
